package com.sailfish.template.infra.common.utils;

import com.sailfish.template.infra.common.constants.ProjectConstant;
import com.sailfish.template.infra.entity.Project;
import com.sailfish.template.infra.exception.AppCommException;
import com.sailfish.template.infra.mapper.project.ProjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * @author XIAXINYU3
 * @date 2021.11.1
 */
@Component
public final class ProjectUtils {

    @Autowired
    ProjectMapper projectMapper;

    /**
     * 获取传统项目id
     *
     * @param iamProjectId 行云项目id
     * @return
     */
    public Long getProjectId(Long iamProjectId) {
        Project project = projectMapper.findOne(iamProjectId);
        if (Objects.isNull(project) || Objects.isNull(project.getId())) {
            throw new AppCommException("project.not.find.error");
        }
        return project.getId();
    }


    /**
     * 获取传统项目id
     *
     * @param iamProjectId 行云项目id
     * @return
     */
    public boolean validate(Long projectId, Long iamProjectId) {
        Long dbProjectId = getProjectId(iamProjectId);
        if (!Objects.equals(dbProjectId, projectId)) {
            throw new AppCommException("project.illegal.error");
        }
        return true;
    }

    /**
     * 生成行云项目编码
     *
     * @return 项目code
     */
    public static String generateCode() {
        return String.format("%s-%s", ProjectConstant.PREFIX,
                new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
    }
}
